package com.dataextend.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dataextend.entity.RequestUserTag;
import com.dataextend.mapper.cluster.UserProfileMapper;
import com.github.pagehelper.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

/**
 *  用户全量标签查询  elasticsearch
 */
@Slf4j
@Service
public class UserTagsServiceV2 {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Value("${usertag_all.usertag_all.index}")
    private String userTagIndex;
    @Value("${usertag_all.usertag_all.source_field}")
    private String userTagSourceField;
    @Value("${usertag_all.usertag_all.type}")
    private String type;
    @Autowired
    private UserProfileMapper userProfileMapper;

    /**
     *  根据用户id查询该用户的全量标签
     * @param cookieid: 33081546482745740
     * @return 用户全量的标签
     */
    private List<JSONObject> elasticsearchCalculate(String cookieid) {
        Map<String, String> codeMaps = new HashMap<>();
        List<JSONObject> tagDefines = userProfileMapper.getTagDefined();
        for (JSONObject tagDefined : tagDefines) {

            String tagId = tagDefined.getString("tag_id");
            String level1Name = tagDefined.getString("level_1_name");
            String level2Name = tagDefined.getString("level_2_name");
            String tagName = tagDefined.getString("tag_name");
            String value = level1Name + "," + level2Name + "," + tagName;
            codeMaps.put(tagId, value);
        }

        log.info(">>>codeMaps:{}" , codeMaps);
        //创建搜索请求对象
        SearchRequest searchRequest = new SearchRequest(userTagIndex);
        String[] source_field_array = userTagSourceField.split(",");

        //设置搜索类型
        searchRequest.types(type);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.fetchSource(source_field_array, new String[]{});

        //创建布尔查询对象
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        boolQueryBuilder.must(QueryBuilders.matchPhraseQuery("userid", cookieid));
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        Map<String, Object> usertags = new HashMap<>();
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest);
            SearchHits hits = searchResponse.getHits();
            SearchHit[] searchHits = hits.getHits();
            for (SearchHit hit : searchHits){
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                usertags = (Map<String, Object>) sourceAsMap.get("tagsmap");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        List<JSONObject> result = new ArrayList<>();
        Iterator<Map.Entry<String, Object>> it = usertags.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Object> entry = it.next();
            String tagId = entry.getKey();
            String tagValue = (String) entry.getValue();
            JSONObject mergeResult = new JSONObject(true);
            if (StringUtil.isEmpty((String) entry.getValue())) {
                mergeResult.put("tagType", codeMaps.get(tagId).split(",")[0]);
                mergeResult.put("tagLevel", codeMaps.get(tagId).split(",")[1]);
                mergeResult.put("tagId", codeMaps.get(tagId).split(",")[2]);
                mergeResult.put("tagWeight", "");
                result.add(mergeResult);
            } else {
                mergeResult.put("tagType", codeMaps.get(tagId).split(",")[0]);
                mergeResult.put("tagLevel", codeMaps.get(tagId).split(",")[1]);
                mergeResult.put("tagId", codeMaps.get(tagId).split(",")[2]);
                mergeResult.put("tagWeight", tagValue);
                result.add(mergeResult);
            }
        }

        return result;
    }



    public JSONObject findUser(RequestUserTag requestUserTag){
        List<JSONObject> cookieInfo =elasticsearchCalculate(requestUserTag.getCookieid());
        JSONObject mergeResult = new JSONObject(true);
        mergeResult.put("cookieId", requestUserTag.getCookieid());
        mergeResult.put("allTags", cookieInfo);
        return mergeResult;
    }


}
